export function sortParams(obj: object): string {
  if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
    return ""; // 如果 obj 不是对象或是数组，直接返回空字符串
  }

  function sortKeys(obj: any): any {
    if (Array.isArray(obj)) {
      return obj
        .filter((item) => item !== undefined && item !== null) // 过滤掉 undefined 和 null
        .map((item) => sortKeys(item))
        .sort();
    } else if (typeof obj === "object" && obj !== null) {
      const sortedObj: Record<string, any> = {};
      Object.keys(obj)
        .sort()
        .forEach((key) => {
          if (typeof obj[key] !== "undefined" && obj[key] !== null) {
            sortedObj[key] = sortKeys(obj[key]);
          }
        });
      return sortedObj;
    }
    return obj;
  }

  const sortedObj = sortKeys(obj);
  return Object.keys(sortedObj)
    .map((key) => {
      const value = sortedObj[key];
      if (
        ["[object Object]", "[object Array]"].includes(
          Object.prototype.toString.call(value)
        )
      ) {
        return `${key}=${JSON.stringify(value)}`;
      } else if (value !== undefined && value !== null) {
        return `${key}=${value}`;
      }
      return ""; // 如果值是 undefined 或 null，返回空字符串
    })
    .filter((item) => item !== "") // 过滤掉空字符串
    .join("&");
}

// 是否文件
export function isFileOrBlob(value: any): boolean {
  return value instanceof File || value instanceof Blob;
}

// 获取地址栏参数
export function getQueryParam(paramName: string) {
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  return urlParams.get(paramName);
}

// 往url拼接参数
export function appendParamsToUrl(
  url: string,
  params: Record<string, string | undefined | null>
): string {
  const filteredParams: Record<string, string> = Object.fromEntries(
    Object.entries(params).filter(([_, value]) => value != null) as [
      string,
      string
    ][]
  );
  const queryString = new URLSearchParams(filteredParams).toString();
  const separator = url.includes("?") ? "&" : "?";
  return `${url}${separator}${queryString}`;
}

// app通讯
type Msg = {
  type: string;
  payload: Record<string, any>;
};
export function postMsg(msg: Msg): void {
  try {
    // @ts-ignore
    window.ReactNativeWebView.postMessage(JSON.stringify(msg));
  } catch (err) {
    // console.error(err)
  }
}
